
#include <Arduino.h>
#include <memory.h>

/** current begining of heap */
extern int  __bss_end;
extern char *__brkval;

#if defined(CORE_TEENSY) || ARDUINO == 104
//extern char __bss_end;
/** \return free heap size */
size_t freeHeap(void) {
  return (char*)RAMEND - (__brkval ? __brkval : &__bss_end)+ 1;
}
#else  // CORE_TEENSY
/** \return free heap size */
size_t freeHeap(void) {
  return (char*)RAMEND - (__brkval ? __brkval : __malloc_heap_start) + 1;
}

// ==================================================================
//   FreeRam
//
//   Return the number of bytes currently free in RAM.
// ==================================================================
int FreeRam (void) 
{
  //extern int  __bss_end;
  //extern int* __brkval;
  int free_memory;
  if (reinterpret_cast<int>(__brkval) == 0) {
    // if no heap use from end of bss section
    free_memory = reinterpret_cast<int>(&free_memory)
                  - reinterpret_cast<int>(&__bss_end);
  } else {
    // use from top of stack to heap
    free_memory = reinterpret_cast<int>(&free_memory)
                  - reinterpret_cast<int>(__brkval);
  }
  return free_memory;
}

#endif  // CORE_TEENSY

